package com.kovell.cairngormlite
{
	
	import com.adobe.cairngorm.control.FrontController;
	
	import flash.utils.getDefinitionByName;
	
	import mx.collections.XMLListCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;

	public class FrontController extends com.adobe.cairngorm.control.FrontController
	{
		
		private static const CONFIG_PATH:String = "config/cairngormlite-config.xml";
		
		public function FrontController()
		{
			init();
		}
		
		private function init():void{
			
			var service:HTTPService = new HTTPService();
			service.url = CONFIG_PATH;
			service.addEventListener(ResultEvent.RESULT, resultHandler);
			service.addEventListener(FaultEvent.FAULT, faultHandler);
			service.resultFormat = "e4x";
			service.useProxy = false;
			service.send();	
		}
		
		private function resultHandler(event:ResultEvent):void	{
			var x:XMLList = new XMLList(event.result.actions.action);
		
			for (var i:int = 0; i < x.length(); i++){
				var id:String = x[i].@id;
				var source:String = x[i].@source;
				var eventName:String = x[i].@event;
				
				var objClass:Class = Class(getDefinitionByName(source));
				
				addCommand(eventName, objClass);
			}
			
		}
		
		private function faultHandler(event:FaultEvent):void{
			trace(event);
			Alert.show(event.toString());
		}
		
	}
}